package com.dbapp.garden.controller.contract;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;

import com.dbapp.garden.entity.SysUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@Controller
public class BaseContractController {

	/**
	 * 获取当前所属园id
	 * 
	 * @param request
	 * @return
	 */
	protected int getSelfGardenId(HttpServletRequest request) {

		return 1;
	}
	
	/**
	 * 获取当前用户
	 * @param request
	 * @return
	 */
	protected SysUser getSelfUser(HttpServletRequest request) {
		
		SysUser ret = new SysUser();
		ret.setId(1);
		return ret;
	}

	protected Map changeObjToMap(Object obj) {
		if (obj == null)
			return null;

		SelfMapper mapper = new SelfMapper();
		String str;
		try {
			str = mapper.writeValueAsString(obj);
			if (StringUtils.isBlank(str))
				return null;
			return mapper.readValue(str, Map.class);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	protected String changeObjToStr(Object obj) {
		if (obj == null)
			return null;

		SelfMapper mapper = new SelfMapper();
		String str;
		try {
			return mapper.writeValueAsString(obj);

		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}

class SelfMapper extends ObjectMapper {
	public SelfMapper() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		this.setDateFormat(df);

		// this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	}
}
